package com.xhh.nphm.gaoxin.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.xhh.nphm.common.annotation.RepeatSubmit;
import com.xhh.nphm.common.constant.Constants;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.PageDomain;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.core.page.TableSupport;
import com.xhh.nphm.common.utils.AcquireWFNoUtils;
import com.xhh.nphm.common.utils.DateUtils;
import com.xhh.nphm.common.utils.ShiroUtils;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.sql.SqlUtil;
import com.xhh.nphm.gaoxin.entity.GxqTtelGetDealEty;
import com.xhh.nphm.gaoxin.entity.GxqTwfSendBackEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormBaseEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormLogEty;
import com.xhh.nphm.gaoxin.service.GxqITelGetDealService;
import com.xhh.nphm.gaoxin.service.GxqITworkFormLogService;
import com.xhh.nphm.gaoxin.service.GxqIWfSendBackService;
import com.xhh.nphm.gaoxin.service.GxqIWorkFormBaseService;
import com.xhh.nphm.system.domain.*;
import com.xhh.nphm.system.mapper.AreaCountyAutoDao;
import com.xhh.nphm.system.service.*;
import com.xhh.nphm.system.service.impl.CommonServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/gaoxin/system/workForm")
public class GxqWorkFormBaseController extends BaseController {
    private String prefix = "system/gaoxin/workForm";
    @Autowired
    private GxqIWorkFormBaseService gxqWorkFormBaseService;
    @Autowired
    private GxqITworkFormLogService gxqTworkFormLogService;
    @Autowired
    private GxqITelGetDealService gxqTelGetDealService;
    @Autowired
    private GxqIWfSendBackService gxqWfSendBackService;
    
    @Autowired
    private CommonServiceImpl commonService;
    @Autowired
    private TmSensitiveTimeService timeService;
    @Autowired
    private TmSensitiveAddressService addressService;
    @Autowired
    private TmSensitiveActionService actionService;
    @Autowired
    private TmSensitiveObjectService objectService;
    @Autowired
    private OpmCrowdService opmCrowdService;
    @Autowired
    private TWorkcsbaseService TWorkcsbaseService;
    @Autowired
    private AreaCountyAutoDao areaCountyAutoDao;
    @Autowired
    private AcquireWFNoUtils acquireWFNoUtils;

    /**
     * 创建工单 页面
     *
     * @param
     * @param map
     * @return
     */
    @GetMapping("/tworkform/{pkId}")
    public ModelAndView workform(@PathVariable("pkId") Integer pkId, ModelMap map) {
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqWorkFormBaseService.getById(pkId);
        if (GxqTworkFormBaseEty != null) {
            GxqTtelGetDealEty telDeal = gxqTelGetDealService.selectByPkId(GxqTworkFormBaseEty.getGetDealPk());
            map.put("workFormBase", GxqTworkFormBaseEty);
            map.put("telDeal", telDeal);
        }
        return new ModelAndView("system/gaoxin/test/tworkformadd");
    }

    /**
     * 电话工单初稿 处理页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/workFormProcess/{pkId}")
    public ModelAndView workFormProcess(@PathVariable("pkId") Integer pkId, ModelMap map) {
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqWorkFormBaseService.getById(pkId);
        if (GxqTworkFormBaseEty != null) {
            GxqTtelGetDealEty telGetDealEty = gxqTelGetDealService.getById(GxqTworkFormBaseEty.getGetDealPk());
            map.put("workFormBase", GxqTworkFormBaseEty);
            map.put("telGetDeal", telGetDealEty);
        }
        return new ModelAndView("system/gaoxin/tworkform/tworkformprocess");
    }

    /**
     * 创建工单
     *
     * @param telRecord
     * @return
     */
    @PostMapping("createWorkform")
    @RepeatSubmit
    public Object createWorkform(GxqTtelGetDealEty telRecord) throws ParseException {
        // TODO: openx和openFrom不清楚页面怎么修改  OriginFlag默认为110
        SysUser user = ShiroUtils.getSysUser();
        // 修改来电记录
        GxqTtelGetDealEty oldTelRecord = gxqTelGetDealService.selectByPkId(telRecord.getPkId());

        // 把来电记录复制给电话工单 并新增电话工单
        GxqTworkFormBaseEty telWorkForm = new GxqTworkFormBaseEty();
        telWorkForm.setFromTelA(telRecord.getFromTelA());
        String wsTopic = "";

        if (StringUtils.isNotEmpty(telRecord.getFromName())) {
            wsTopic = telRecord.getFromName();
        }
        if (StringUtils.isNotEmpty(telRecord.getDcntAname())) {
            wsTopic = wsTopic + "[" + telRecord.getDfmClaName() + "]";
        }
        if (StringUtils.isNotEmpty(telRecord.getDfmClaName())) {
            wsTopic += telRecord.getDcntAname();
        }
        telWorkForm.setWsTopic(wsTopic);
        telWorkForm.setSpareInt(0);
        telWorkForm.setMark(String.valueOf(telRecord.getMark()));
        telWorkForm.setCallId(telRecord.getCallId());
        telWorkForm.setTapeId(telRecord.getTapeId());
        telWorkForm.setFmCerName(oldTelRecord.getFmCerName());
        telWorkForm.setFmCerNo(oldTelRecord.getFmCerNo());
        telWorkForm.setFmContent(telRecord.getFmContent());
        telWorkForm.setFromName(telRecord.getFromName());
        telWorkForm.setWsCode(telRecord.getWsCode());
        telWorkForm.setWsKey(telRecord.getWsKey());
        telWorkForm.setDcntAcode(telRecord.getDcntAcode());
        telWorkForm.setDcntAname(telRecord.getDcntAname());
        telWorkForm.setDfmClaNo(telRecord.getDfmClaNo());
        telWorkForm.setDfmClaName(telRecord.getDfmClaName());
        telWorkForm.setAccSubject(telRecord.getAccSubject());
        telWorkForm.setGetDealPk(telRecord.getPkId());
        telWorkForm.setKeyWord(telRecord.getKeyWord());
        telWorkForm.setFmAddress(telRecord.getFmAddress());
        // 设置地区 ？？？
        telWorkForm.setFmAreaNo(oldTelRecord.getFmAreaNo());
        telWorkForm.setFmAreaName(oldTelRecord.getFmAreaName());
        telWorkForm.setOpenFrom(telRecord.getOpenFrom());
        telWorkForm.setOpenX(telRecord.getOpenX());
        // 设置创建工单的人
        telWorkForm.setIptWorker(user.getUserName());
        telWorkForm.setIptWorkNo(user.getUserNo());
        // 新增电话工单 设置工单创建时间
        telWorkForm.setIptTime(new Date());
        telWorkForm.setCrtStepTime(new Date());
        telWorkForm.setOriginFlag(110);
        telWorkForm.setCrtStepTime(new Date());
        telWorkForm.setCrtStepId(100);
        telWorkForm.setCrtStepName("初稿");
        // 设置工单性质为普通工单
        telWorkForm.setSetProId(11);
        telWorkForm.setSetProName("普通工单");
        String workFormNo;
        if(acquireWFNoUtils.isEnable()){
            String telWFNo = acquireWFNoUtils.getTelWFNo();
            if(Objects.equals(telWFNo,"")){
                workFormNo = commonService.byWFGetNO(5);
                acquireWFNoUtils.renewValue(Constants.TEL_NO_COUNT_KEY);
            }else{
                workFormNo = telWFNo;
            }
        }else{
            workFormNo = commonService.byWFGetNO(5);
        }
        telWorkForm.setWorkFormNo(workFormNo);
        telWorkForm.setMyTmLmt(commonService.getNxetBackLimit(5));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date myTmLmt = format.parse(telWorkForm.getMyTmLmt());
        telWorkForm.setWfLimit(myTmLmt);
        telWorkForm.setWfDefer(myTmLmt);
        // 设置工单的特殊等级（特殊时间、特殊地点、特殊行为、特殊对象）每符合一个，等级加1
        int specialLevel = 0;
        List<TmSensitiveTime> timeList = timeService.listJson(null);
        Date curDate = DateUtils.getNowDate();
        for (TmSensitiveTime temp : timeList) {
            // 当前时间是否被包含在特殊时间段中
            if (curDate.after(temp.getSensitiveStartTime()) && curDate.before(temp.getSensitiveEndTime())) {
                specialLevel += 1;
                break;
            }
        }
        List<TmSensitiveAddress> addressList = addressService.listJson(null);
        String fmContent = telRecord.getFmContent();
        for (TmSensitiveAddress temp : addressList) {
            // 当前地点是否是特殊地点
            // TODO 现使用来电内容来匹配特殊地点，后会使用归一地址作为匹配
            if (fmContent.contains(temp.getSensitiveAddress())) {
                specialLevel += 1;
                break;
            }
        }
        List<TmSensitiveAction> actionList = actionService.listJson(null);
        for (TmSensitiveAction temp : actionList) {
            //来电内容是否包含特殊行为
            if (fmContent.contains(temp.getSensitiveAction())) {
                specialLevel += 1;
                break;
            }
        }
        List<TmSensitiveObject> objectList = objectService.listJson(null);
        for (TmSensitiveObject temp : objectList) {
            //来电内容是否包含特殊行为
            if (fmContent.contains(temp.getSensitiveName())) {
                specialLevel += 1;
                break;
            }
        }
        //设置工单的特殊等级
        telWorkForm.setSpecialLevel(specialLevel);

        int rows = 0;
        boolean flag = gxqWorkFormBaseService.save(telWorkForm);

        // 记录电话工单操作日志
        if (flag) {
            rows = 1;
            GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
            etyLog.setWfId(telWorkForm.getPkId());
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpAction("创建");
            etyLog.setOpBtnId(-1);
            etyLog.setWsDesc("创建工单");
            etyLog.setWsOpen(0);
            etyLog.setOpDesc("创建工单");
            etyLog.setEffectFlag(-1);
            gxqTworkFormLogService.save(etyLog);

            // 反向更新电话记录
            if (oldTelRecord != null) {
//                GxqTtelGetDealEty updateTelRecord = new GxqTtelGetDealEty();
//                updateTelRecord.setPkId(oldTelRecord.getPkId());
//                updateTelRecord.setYworkNo(user.getUserNo());
//                updateTelRecord.setYworker(user.getUserName());
//                updateTelRecord.setYdealDesc("创建工单");
//                updateTelRecord.setYsysDesc("创建工单");
//                updateTelRecord.setWkPkId(telWorkForm.getPkId());
//                updateTelRecord.setWkFmNo(telWorkForm.getWorkFormNo());
//                updateTelRecord.setWfSltKey(telWorkForm.getWsTopic());
//                updateTelRecord.setStateFlag(125);
//                updateTelRecord.setStateDesc("转入工单处理");
//                updateTelRecord.setAutoGetFlag(0);
//                updateTelRecord.setYeditTime(new Date());
//                //是否创建工单标志
//                updateTelRecord.setWkFmFlag(1);
//                //oldTelRecord.setOpenX(telWorkForm.getOpenX());
//                gxqTelGetDealService.whenWFCreateSet(updateTelRecord);

                UpdateWrapper<GxqTtelGetDealEty> updateWrapper = new UpdateWrapper<>();
                updateWrapper.setSql("yeditTime=getdate()");
                updateWrapper.lambda().eq(GxqTtelGetDealEty::getPkId, oldTelRecord.getPkId())
                        .set(GxqTtelGetDealEty::getYworkNo, user.getUserNo())
                        .set(GxqTtelGetDealEty::getYworker, user.getUserName())
                        .set(GxqTtelGetDealEty::getWkPkId, telWorkForm.getPkId())
                        .set(GxqTtelGetDealEty::getWkFmNo, telWorkForm.getWorkFormNo())
                        .set(GxqTtelGetDealEty::getWfSltKey, telWorkForm.getWsTopic())
                        .set(GxqTtelGetDealEty::getWkFmFlag, 1)
                        .set(GxqTtelGetDealEty::getStateFlag, 125)
                        .set(GxqTtelGetDealEty::getStateDesc, "转入工单处理")
                        .set(GxqTtelGetDealEty::getYdealDesc, "创建工单")
                        .set(GxqTtelGetDealEty::getYsysDesc, "创建工单");
                gxqTelGetDealService.update(null, updateWrapper);
            }
        }
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("pkId", telWorkForm.getPkId());
        ajaxResult.put("msg", "操作成功");
        ajaxResult.put("code", 0);
        return ajaxResult;
    }

    /**
     * 通过工单
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("pass")
    @RepeatSubmit
    public AjaxResult pass(GxqTworkFormBaseEty GxqTworkFormBaseEty) {
        GxqTworkFormBaseEty workForm = gxqWorkFormBaseService.getById(GxqTworkFormBaseEty.getPkId());
        List<GxqTwfSendBackEty> twfSendBackEties = gxqWfSendBackService.selectByWfId(GxqTworkFormBaseEty.getPkId());
        UpdateWrapper<GxqTworkFormBaseEty> updateWrapper = new UpdateWrapper<>();
        if (twfSendBackEties.size() > 0) {
            updateWrapper.eq("PkId", workForm.getPkId());
            updateWrapper.set("CrtStepID", 103);
            updateWrapper.set("CrtStepName", "审查工单");
            updateWrapper.set("CrtStepTime", new Date());
        } else {
            updateWrapper.eq("PkId", workForm.getPkId());
            updateWrapper.set("CrtStepID", 100);
            updateWrapper.set("CrtStepName", "初稿");
            updateWrapper.set("CrtStepTime", new Date());
        }
        return toAjax(gxqWorkFormBaseService.update(null, updateWrapper));
    }

    /**
     * 通过并派单
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("dispatch")
    @RepeatSubmit
    public AjaxResult dispatch(GxqTworkFormBaseEty GxqTworkFormBaseEty,String twsf) {
        //保存响应结果
        boolean flag = false;
        //校验方法入参是否为空
        if (GxqTworkFormBaseEty != null) {
            SysUser user = ShiroUtils.getSysUser();
            UpdateWrapper<GxqTworkFormBaseEty> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("PkId", GxqTworkFormBaseEty.getPkId());
            updateWrapper.set("CrtStepID", GxqTworkFormBaseEty.getCrtStepId());
            updateWrapper.set("CrtStepName", GxqTworkFormBaseEty.getCrtStepName());
            updateWrapper.set("WsUFlag", 1);
            updateWrapper.set("IptWorkNo", user.getUserNo());
            updateWrapper.set("IptWorker", user.getUserName());
            //修改工单信息
            flag = gxqWorkFormBaseService.update(null, updateWrapper);
            //封装工单操作日志
            dispatchTwfLog(GxqTworkFormBaseEty, user);
            //更新电话记录和工单操作日志
            if (GxqTworkFormBaseEty.getGetDealPk() > 0) {
                GxqTtelGetDealEty GxqTtelGetDealEty = gxqTelGetDealService.selectByPkId(GxqTworkFormBaseEty.getGetDealPk());
                UpdateWrapper<GxqTtelGetDealEty> wrapper = new UpdateWrapper<>();
                wrapper.eq("PkId", GxqTworkFormBaseEty.getGetDealPk());
                wrapper.set("OpenX", GxqTworkFormBaseEty.getOpenX());
                wrapper.set("StateDesc", "审定工单");
                wrapper.set("AutoGetFlag", 0);
                gxqTelGetDealService.update(null, wrapper);
            }
            //封装OpmCrowd记录
            OpmCrowd opmCrowd = dispatchOpmCrowd(GxqTworkFormBaseEty, user);
            //新增OpmCrowd记录
            opmCrowdService.save(opmCrowd);
            List<GxqTwfSendBackEty> twfSendBackEties = JSON.parseArray(twsf, GxqTwfSendBackEty.class);
            for (GxqTwfSendBackEty GxqTwfSendBackEty : twfSendBackEties) {
                AreaCountyAuto areaCountyAuto = areaCountyAutoDao.selectDeptAuto(GxqTwfSendBackEty.getSbdeptId(), GxqTwfSendBackEty.getSbdeptName());
                if (areaCountyAuto != null) {
                    if (GxqTwfSendBackEty.getSbdeptName().equals(areaCountyAuto.getDeptName()) && GxqTwfSendBackEty.getSbdeptId().equals(areaCountyAuto.getDeptId()) && areaCountyAuto.getAutoSign() == 1) {
                        Date date = new Date();
                        GxqTworkFormBaseEty tworkFormBase = gxqWorkFormBaseService.getById(GxqTworkFormBaseEty.getPkId());
                        // 更新工单
                        UpdateWrapper<GxqTworkFormBaseEty> update = new UpdateWrapper<>();
                        update.eq("PkId", tworkFormBase.getPkId());
                        update.set("WsUFlag", 1);
                        update.set("CrtStepID", 400);
                        update.set("CrtStepName", "市级主办处理中");
                        update.set("CrtStepTime", date);
                        gxqWorkFormBaseService.update(null, updateWrapper);
                        // 更新派单
                        UpdateWrapper<GxqTwfSendBackEty> wrapper = new UpdateWrapper<>();
                        wrapper.eq("PkId", GxqTwfSendBackEty.getPkId());
                        wrapper.set("SendState", 21);
                        wrapper.set("GetTime", date);
                        wrapper.set("PromisesTime", commonService.getNxetBackLimit(5));
                        wrapper.set("BackState", 0);
                        wrapper.set("GetPerson", user.getUserNo());
                        wrapper.set("GetPerTel", user.getPhonenumber());
                        wrapper.set("BackRemark", GxqTwfSendBackEty.getBackRemark());
                        boolean flag1 = gxqWfSendBackService.update(null, wrapper);
                        // 派单更新成功 新增日志
                        if (flag1) {
                            GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
                            etyLog.setWfId(GxqTwfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                            etyLog.setOpDeptNo(user.getDeptId().toString());
                            etyLog.setOpDeptName(user.getDeptName());
                            etyLog.setOpUserNo(user.getUserNo());
                            etyLog.setOpUserName(user.getUserName());
                            etyLog.setOpBtnId(-1);
                            etyLog.setOpAction("签收");
                            etyLog.setWsDesc("签收工单。"); //Show In website
                            etyLog.setWsOpen(1); //website ShowFlag
                            etyLog.setEffectFlag(1);
                            String signDesc = GxqTwfSendBackEty.getSendRemark();
//                            signDesc = "后续本单位办理（" + signDesc + "）";
                            signDesc = signDesc == null ? "后续本单位办理": "后续本单位办理（" + signDesc + "）";
                            etyLog.setOpDesc(signDesc);
                            gxqTworkFormLogService.save(etyLog);
                        }
                    }
                }
            }
        }
        return toAjax(flag);
    }

    /**
     * 结束派单
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("shutdown")
    @RepeatSubmit
    public AjaxResult shutdown(GxqTworkFormBaseEty GxqTworkFormBaseEty) {
        //保存响应结果
        boolean flag = false;
        //校验方法入参是否为空
        if (GxqTworkFormBaseEty != null) {
            SysUser user = ShiroUtils.getSysUser();
            UpdateWrapper<GxqTworkFormBaseEty> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("PkId", GxqTworkFormBaseEty.getPkId());
            updateWrapper.set("CrtStepID", 960);
            updateWrapper.set("CrtStepName", "强制结束");
            updateWrapper.set("WsUFlag", 1);
            updateWrapper.set("IptWorkNo", user.getUserNo());
            updateWrapper.set("IptWorker", user.getUserName());
            //修改工单信息
            flag = gxqWorkFormBaseService.update(null, updateWrapper);
            //封装工单操作日志
            dispatchTwfLog(GxqTworkFormBaseEty, user);
            //更新电话记录和工单操作日志
            if (GxqTworkFormBaseEty.getGetDealPk() > 0) {
                GxqTtelGetDealEty GxqTtelGetDealEty = gxqTelGetDealService.selectByPkId(GxqTworkFormBaseEty.getGetDealPk());
                UpdateWrapper<GxqTtelGetDealEty> wrapper = new UpdateWrapper<>();
                wrapper.eq("PkId", GxqTworkFormBaseEty.getGetDealPk());
                wrapper.set("OpenX", GxqTworkFormBaseEty.getOpenX());
                wrapper.set("StateDesc", "结束");
                wrapper.set("AutoGetFlag", 0);
                gxqTelGetDealService.update(null, wrapper);
            }
            //封装OpmCrowd记录
            OpmCrowd opmCrowd = dispatchOpmCrowd(GxqTworkFormBaseEty, user);
            //新增OpmCrowd记录
            opmCrowdService.save(opmCrowd);
        }
        return toAjax(flag);
    }


    /**
     * 通过并派单-封装OpmCrowd记录
     *
     * @param GxqTworkFormBaseEty 工单信息
     * @param user             当前登录用户信息
     * @return opmCrowd对象
     */
    private OpmCrowd dispatchOpmCrowd(GxqTworkFormBaseEty GxqTworkFormBaseEty, SysUser user) {
        OpmCrowd opmCrowd = new OpmCrowd();
        String msg = "成都12345温馨提示：您的来电已受理（流水号：{0}；提取码：{1}），可以通过网站（http://12345.chengdu.gov.cn）进行查询，谢谢。";
        msg = msg.replace("{0}", GxqTworkFormBaseEty.getWsCode()).replace("{1}", GxqTworkFormBaseEty.getWsKey());
        //电话单
        opmCrowd.setFlagOrigin(11);
        opmCrowd.setWorkFormPK(GxqTworkFormBaseEty.getPkId());
        opmCrowd.setIptUserNo(user.getUserNo());
        opmCrowd.setIptWorker(user.getUserName());
        opmCrowd.setIptTime(new Date());
        //create
        opmCrowd.setFlagSort("101");
        opmCrowd.setMsgPhone(GxqTworkFormBaseEty.getFromTelA());
        opmCrowd.setMsgCnnt(msg);
        opmCrowd.setMsgSign("");
        //wait send
        opmCrowd.setFlagSend(0);
        return opmCrowd;
    }

    /**
     * 通过并派单-封装工单操作日志
     *
     * @param GxqTworkFormBaseEty 工单信息
     * @param user             当前登录用户
     */
    private void dispatchTwfLog(GxqTworkFormBaseEty GxqTworkFormBaseEty, SysUser user) {
        //封装工单操作日志
        GxqTworkFormLogEty GxqTworkFormLogEty = GxqTworkFormBaseEty.getTworkFormLogEty();
        //[tWorkFormBase]PkId
        GxqTworkFormLogEty.setWfId(GxqTworkFormBaseEty.getPkId());
        GxqTworkFormLogEty.setOpDeptNo(user.getDeptId().toString());
        GxqTworkFormLogEty.setOpDeptName(user.getDeptName());
        GxqTworkFormLogEty.setOpUserNo(user.getUserNo());
        GxqTworkFormLogEty.setOpUserName(user.getUserName());
        GxqTworkFormLogEty.setOpAction("审核工单");
        GxqTworkFormLogEty.setOpBtnId(-1);
        GxqTworkFormLogEty.setWsDesc("派发工单");
        GxqTworkFormLogEty.setWsOpen(0);
        GxqTworkFormLogEty.setOpDesc("审核工单");
        GxqTworkFormLogEty.setEffectFlag(-1);
        gxqTworkFormLogService.save(GxqTworkFormLogEty);
    }


    /**
     * 进入电话工单初稿列表页面
     *
     * @return
     */
    @GetMapping("/twfDraftList")
    public ModelAndView twfDraftList() {
        return new ModelAndView("system/gaoxin/tworkform/twfDraftList");
    }

    /**
     * 加载电话工单初稿列表数据
     */
    @PostMapping("/twfDraftListJson")
    public Object twfDraftListJson(GxqTworkFormBaseEty twfb) {
        //分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy2());
            if (StringUtils.isEmpty(orderBy)) {
                orderBy = "CHARINDEX('110转接',FromName) desc,mark desc,PkId desc";
            }
            PageHelper.startPage(pageNum, pageSize, orderBy);
        } else {
            pageNum = 1;
            pageSize = 5;
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy2());
            if (StringUtils.isEmpty(orderBy)) {
                orderBy = "CHARINDEX('110转接',FromName) desc,mark desc,PkId desc,";
            }
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
        //获取电话工单初稿列表数据
        List<GxqTworkFormBaseEty> list = gxqWorkFormBaseService.findTwfDraftList(twfb);
        return getDataTable(list);
    }

    /**
     * 进入到电话工单初稿新增页面
     */
    @GetMapping("/toAdd")
    public ModelAndView add() {
        return new ModelAndView("system/gaoxin/tworkform/tworkformadd");
    }

    /**
     * 新增电话工单初稿
     *
     * @param GxqTworkFormBaseEty 电话工单实体信息
     * @return 操作结果
     */
    @PostMapping("/add")
    public AjaxResult add(GxqTworkFormBaseEty GxqTworkFormBaseEty) {
        return toAjax(gxqWorkFormBaseService.insert(GxqTworkFormBaseEty));
    }


    /**
     * 进入电话工单初稿编辑页面
     *
     * @return
     */
    @GetMapping("/edit/{pkId}")
    public ModelAndView edit(@PathVariable("pkId") Integer pkId, ModelMap map) {
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqWorkFormBaseService.getById(pkId);
        if (GxqTworkFormBaseEty != null) {
            map.put("workFormBase", GxqTworkFormBaseEty);
        }
        return new ModelAndView("system/gaoxin/tworkform/tworkformedit");
    }

    /**
     * 修改工单
     *
     * @param GxqTworkFormBaseEty
     * @return
     */
    @PostMapping("/update")
    @RepeatSubmit
    public AjaxResult update(GxqTworkFormBaseEty GxqTworkFormBaseEty) {
        GxqTworkFormBaseEty tworkFormBase = gxqWorkFormBaseService.getById(GxqTworkFormBaseEty.getPkId());
//        tworkFormBase.setDcntAcode(GxqTworkFormBaseEty.getDcntAcode());
//        tworkFormBase.setDcntAname(GxqTworkFormBaseEty.getDcntAname());
//        tworkFormBase.setDfmClaNo(GxqTworkFormBaseEty.getDfmClaNo());
//        tworkFormBase.setDfmClaName(GxqTworkFormBaseEty.getDfmClaName());
        tworkFormBase.setWsTopic(GxqTworkFormBaseEty.getWsTopic());
        tworkFormBase.setSetProId(GxqTworkFormBaseEty.getSetProId());
        tworkFormBase.setSetProName(GxqTworkFormBaseEty.getSetProName());
        tworkFormBase.setWfRemark(GxqTworkFormBaseEty.getWfRemark());
        tworkFormBase.setOpenX(GxqTworkFormBaseEty.getOpenX());
        tworkFormBase.setReportFlag(GxqTworkFormBaseEty.getReportFlag());
        tworkFormBase.setWfLimit(GxqTworkFormBaseEty.getWfLimit());
        //通过派单设置为审查工单
        tworkFormBase.setCrtStepId(103);
        tworkFormBase.setCrtStepName("审查工单");


        SysUser user = ShiroUtils.getSysUser();
        GxqTworkFormLogEty GxqTworkFormLogEty = GxqTworkFormBaseEty.getTworkFormLogEty();
        GxqTworkFormLogEty.setOpDeptNo(user.getDeptId().toString());
        GxqTworkFormLogEty.setOpDeptName(user.getDeptName());
        GxqTworkFormLogEty.setOpUserNo(user.getUserNo());
        GxqTworkFormLogEty.setOpUserName(user.getUserName());
        GxqTworkFormLogEty.setOpAction("创建工单");
        GxqTworkFormLogEty.setOpBtnId(-1);
        GxqTtelGetDealEty GxqTtelGetDealEty = gxqTelGetDealService.selectByPkId(tworkFormBase.getGetDealPk());
        GxqTtelGetDealEty.setYdealDesc("创建工单");
        GxqTtelGetDealEty.setYsysDesc("创建工单");
        GxqTtelGetDealEty.setStateFlag(125);
        gxqTelGetDealService.update(GxqTtelGetDealEty);
        return toAjax(gxqWorkFormBaseService.saveWorkForm(tworkFormBase, GxqTworkFormLogEty));
    }

    /**
     * 拟派工单页面的保存按钮
     *
     * @param GxqTworkFormBaseEty
     * @return 响应结果
     */
    @PostMapping("/updateWorkForm")
    public AjaxResult updateWorkForm(GxqTworkFormBaseEty GxqTworkFormBaseEty) {
        GxqTworkFormBaseEty tworkFormBase = gxqWorkFormBaseService.getById(GxqTworkFormBaseEty.getPkId());
        tworkFormBase.setDcntAcode(GxqTworkFormBaseEty.getDcntAcode());
        tworkFormBase.setDcntAname(GxqTworkFormBaseEty.getDcntAname());
        tworkFormBase.setDfmClaNo(GxqTworkFormBaseEty.getDfmClaNo());
        tworkFormBase.setDfmClaName(GxqTworkFormBaseEty.getDfmClaName());
        tworkFormBase.setFmContent(GxqTworkFormBaseEty.getFmContent());
        tworkFormBase.setFmAreaNo(GxqTworkFormBaseEty.getFmAreaNo());
        tworkFormBase.setFmAreaName(GxqTworkFormBaseEty.getFmAreaName());
        tworkFormBase.setWsTopic(GxqTworkFormBaseEty.getWsTopic());
        tworkFormBase.setWfRemark(GxqTworkFormBaseEty.getWfRemark());
        tworkFormBase.setWfLimit(GxqTworkFormBaseEty.getWfLimit());
        return toAjax(gxqWorkFormBaseService.saveOrUpdate(tworkFormBase));
    }

    /**
     * 进入网评不满意工单列表页面
     *
     * @return
     */
    @GetMapping("/badCommentTwfbList")
    public ModelAndView badCommentTwfbList() {
        return new ModelAndView("system/gaoxin/tworkform/badCommentList");
    }

    /**
     * 加载网评不满意工单列表数据
     */
    @PostMapping("/badCommentTwfbListJson")
    public Object badCommentTwfbListJson(GxqTworkFormBaseEty twfb) {
        startPage();
        //获取网评不满意工单列表数据
        List<GxqTworkFormBaseEty> list = gxqWorkFormBaseService.findBadCommentTwfbList(twfb);
        return getDataTable(list);
    }

    /**
     * 查询电话工单操作日志
     */
    @GetMapping("workFormLog/{wfId}")
    public ModelAndView operationLog(@PathVariable("wfId") Integer wfId, ModelMap map) {
        List<GxqTworkFormLogEty> workFormLogList = gxqTworkFormLogService.logListJson(wfId);
        map.put("workFormLogList", workFormLogList);
        return new ModelAndView("system/gaoxin/tworkform/workFormLogbak");
    }

    @GetMapping("/workFormLog")
    public ModelAndView workFormLog(int pkId, HttpServletRequest request) {
        request.setAttribute("pkId", pkId);
        return new ModelAndView("system/gaoxin/tworkform/workFormLog");
    }

    /**
     * 操作记录列表
     *
     * @param pkId
     * @return
     */
    @RequestMapping("/workFormLogList")
    public TableDataInfo workFormLogList(int pkId) {
        startPage();
        List<GxqTworkFormLogEty> list = gxqTworkFormLogService.logListJson(pkId);
        return getDataTable(list);
    }

    /**
     * 抄送件
     *  将工单抄送到指定部门
     * @param wfId 工单编号
     * @param deptNos 部门编号集
     * @return 响应结果
     */
    @PostMapping("/copy")
    public AjaxResult copy(Integer wfId,String deptNos,String deptNames){
        if (Objects.equals(deptNames, "")){
            return AjaxResult.success();
        }
        return toAjax(TWorkcsbaseService.copy(wfId,deptNos,deptNames));
    }

    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String... ids) {
        return toAjax(gxqWorkFormBaseService.removeByIds(Arrays.asList(ids)));
    }

}